package com.yingside.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yingside.common.util.TreeUtil;
import com.yingside.system.model.Menu;
import com.yingside.system.model.User;
import com.yingside.system.mapper.UserMapper;
import com.yingside.system.service.IMenuService;
import com.yingside.system.service.IOperatorService;
import com.yingside.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yingside
 * @since 2020-12-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IOperatorService operatorService;

    @Override
    public User selectUserByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
    }

    @Override
    public IPage<User> selectAllWithDept(Integer page, Integer limit, User userQuery) {
        Page<User> pages = new Page<>((page - 1),limit);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(userQuery != null){
            queryWrapper.eq(userQuery.getUsername() != null && !userQuery.getUsername().equals(""),"username",userQuery.getUsername());
            queryWrapper.eq(userQuery.getEmail() != null && !userQuery.getEmail().equals(""),"email",userQuery.getEmail());
            queryWrapper.eq(userQuery.getStatus() != null,"status",userQuery.getStatus());
            queryWrapper.eq(userQuery.getDeptId() != null,"dept_id",userQuery.getDeptId());
        }

        IPage<User> userPage = userMapper.selectAllWithDept(pages, queryWrapper);
        return userPage;
    }

    @Override
    public Set<String> selectRoleNameByUserName(String username) {
        return userMapper.selectRoleNameByUserName(username);
    }

    @Override
    public Set<String> selectPermsByUsername(String username) {
        Set<String> perms = new HashSet<>();
        List<Menu> menuTree = menuService.selectMenuTreeByUsername(username);
        List<Menu> leafNodeMenuList = TreeUtil.getAllLeafNode(menuTree);
        // 循环添加所有菜单权限
        for (Menu menu : leafNodeMenuList) {
            perms.add(menu.getPerms());
        }
        // 添加该用户所有操作权限
        perms.addAll(selectOperatorPermsByUserName(username));
        return perms;
    }

    @Override
    public Set<String> selectOperatorPermsByUserName(String username) {
        return userMapper.selectOperatorPermsByUserName(username);
    }
}
